package com.bj58.groupbuy.action.controllers;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.ServletRequestUtils;

import com.bj58.groupbuy.action.interceptors.Check;
import com.bj58.groupbuy.action.model.UploadDocInfo;
import com.bj58.groupbuy.action.model.User;
import com.bj58.groupbuy.action.service.UploadDocInfoService;
import com.bj58.groupbuy.action.util.MyPathUtil;
import com.bj58.groupbuy.action.util.MyPdf2swf;
import com.bj58.groupbuy.action.util.MyStore;
import com.bj58.groupbuy.action.util.SomePublicUtil;
import com.bj58.groupbuy.action.util.TemplateMethodFactory;
import com.bj58.groupbuy.action.util.VelocityTools;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.wf.page.Paginate;
import com.bj58.wf.mvc.ActionResult;
import com.bj58.wf.mvc.BeatContext;
import com.bj58.wf.mvc.BeatContext.Model;
import com.bj58.wf.mvc.MvcController;
import com.bj58.wf.mvc.actionresult.ContentResult;
import com.bj58.wf.mvc.annotation.GET;
import com.bj58.wf.mvc.annotation.POST;
import com.bj58.wf.mvc.annotation.Path;
import com.bj58.wf.mvc.client.RequestFile;
import com.bj58.wf.util.FileUtil;

@Path("uploadDoc")
public class UploadPDFController extends MvcController{
//	private UserManagerService userManagerService = ServiceLocator.get(UserManagerService.class);
	private SomePublicUtil spu = new SomePublicUtil();
	private static HashMap<String,String> acceptTypeMap =new HashMap<String,String>();
	static{
		acceptTypeMap.put("application/msword", "application/msword");
		acceptTypeMap.put("application/vnd.ms-powerpoint", "application/vnd.ms-powerpoint");
		acceptTypeMap.put("application/vnd.ms-excel", "application/vnd.ms-excel");
		acceptTypeMap.put("application/pdf", "application/pdf");
		acceptTypeMap.put("doc", "application/msword");
		acceptTypeMap.put("docx", "application/msword");
		acceptTypeMap.put("ppt", "application/vnd.ms-powerpoint");
		acceptTypeMap.put("pptx", "application/vnd.ms-powerpoint");
		acceptTypeMap.put("pps", "application/vnd.ms-powerpoint");
		acceptTypeMap.put("ppsx", "application/vnd.ms-powerpoint");
		acceptTypeMap.put("xls", "application/vnd.ms-excel");
		acceptTypeMap.put("xlsx", "application/vnd.ms-excel");
		acceptTypeMap.put("pdf", "application/pdf");
		acceptTypeMap.put("zip", "zip");
	}
	
	UploadDocInfoService uploadService = ServiceLocator.get(UploadDocInfoService.class);
	
	/**
	 * 文档管理
	 * @return
	 */
	@Path("manage/{option}")
	@Check("uploadDoc/manage/manage")
	@POST
	@GET
	public ActionResult toupload(String option) {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		TemplateMethodFactory.setVelocityContext("tools",VelocityTools.class, model);
		String returnUrl = "uploadDoc/docManage";
		try {
			if ("toupload".equalsIgnoreCase(option)) {
				//文件类别一
				List<String> cate1List = uploadService.getAllFileCate1();
				model.add("cate1List",cate1List);
				//文件类别二
//				List<String> cate2List = uploadService.getAllFileCate2();
//				model.add("cate2List",cate2List);
				returnUrl = "uploadDoc/toUploadDoc";
			}else if("manage".equals(option)){
				String initalFileName = ServletRequestUtils.getStringParameter(request, "initalFileName","");
				String fileCate1 = ServletRequestUtils.getStringParameter(request, "fileCate1","");
				String fileCate2 = ServletRequestUtils.getStringParameter(request, "fileCate2","");
//				String fileDescribe = ServletRequestUtils.getStringParameter(request, "fileDescribe","");
				int pageIndex = ServletRequestUtils.getIntParameter(request, "pageindex", 0);
				//查询条件组织 以及分页查询参数组织
				StringBuffer where = new StringBuffer(); //查询条件
				StringBuffer url = new StringBuffer(); //分页查询参数
				where.append(" state = 1 ");
				if(!"".equals(initalFileName)){
					where.append(" & initalFileName ? '%"+initalFileName+"%'");
					url.append("&initalFileName="+initalFileName);
				}
				if(!"".equals(fileCate1)){
					where.append(" &  fileCate1 ? '%"+fileCate1+"%'");
					url.append("&fileCate1="+fileCate1);
				}
				if(!"".equals(fileCate2)){
					where.append(" &  fileCate2 ? '%"+fileCate2+"%'");
					url.append("&fileCate2="+fileCate2);
				}
				//文件类别一
				List<String> cate1List = uploadService.getAllFileCate1();
				//文件类别二
				List<String> cate2List = uploadService.getAllFileCate2(fileCate1);
				model.add("cate1List",cate1List);
				model.add("cate2List",cate2List);
				//分页查询
				Paginate<UploadDocInfo> pList;
				User user = spu.getUserByCookie(request);
				if(!MyStore.admin.equals(user.getFunction())){	//不是管理员只能管理自己上传的文档
					where.append(" &  fileCreater='"+user.getUsername()+"'");
				}
				pList = uploadService.getListByPage(where.toString(),pageIndex, 20);
			
				model.add("pList",pList);
				if(pList !=null)
					model.add("rsList",pList.getItems());	
				model.add("paramurl",url.toString());
				model.add("initalFileName",initalFileName);
				model.add("fileCate1",fileCate1);
				model.add("fileCate2",fileCate2);
				returnUrl = "uploadDoc/docManage";
			}else if("changeState".equals(option)){
				int id = ServletRequestUtils.getIntParameter(request, "id", 0);
				int upstate = ServletRequestUtils.getIntParameter(request, "upstate", -1);
				if(id == 0 || upstate == -1){
					return new ContentResult("error");
				}
				UploadDocInfo docInfo= uploadService.findById(UploadDocInfo.class,"*", id);
				docInfo.setState(upstate);
				deleteFile(docInfo.getSaveName());
				if(!uploadService.update(docInfo))
					return new ContentResult("error");
				else
					return new ContentResult("success");
			}else if("toEdit".equals(option)){
				int id = ServletRequestUtils.getIntParameter(request, "id", 0);
				UploadDocInfo docInfo= uploadService.findById(UploadDocInfo.class,"*", id);
				//文件类别一
				List<String> cate1List = uploadService.getAllFileCate1();
				//文件类别二
				List<String> cate2List = uploadService.getAllFileCate2(docInfo.getFileCate1());
				model.add("cate1List",cate1List);
				model.add("cate2List",cate2List);
				model.add("vo",docInfo);
				 returnUrl = "uploadDoc/editFileInfo";
			}
			return ActionResult.view(returnUrl);
		} catch (Exception e) {
			e.printStackTrace();
			return new ContentResult("error");
		}
	}
	
	/**
	 * 文档列表查看
	 * @return
	 */
	@Path("list")
	@Check("uploadDoc/list")
	@POST
	@GET
	public ActionResult showList() {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		TemplateMethodFactory.setVelocityContext("tools",VelocityTools.class, model);
		String returnUrl = "uploadDoc/docManage";
		try {
				String initalFileName = ServletRequestUtils.getStringParameter(request, "initalFileName","");
				String fileCate1 = ServletRequestUtils.getStringParameter(request, "fileCate1","");
				String fileCate2 = ServletRequestUtils.getStringParameter(request, "fileCate2","");
				int pageIndex = ServletRequestUtils.getIntParameter(request, "pageindex", 0);
				//查询条件组织 以及分页查询参数组织
				StringBuffer where = new StringBuffer(); //查询条件
				StringBuffer url = new StringBuffer(); //分页查询参数
				where.append(" state = 1 ");
				if(!"".equals(initalFileName)){
					where.append(" & initalFileName ? '%"+initalFileName+"%'");
					url.append("&initalFileName="+initalFileName);
				}
				if(!"".equals(fileCate1)){
					where.append(" &  fileCate1 ? '%"+fileCate1+"%'");
					url.append("&fileCate1="+fileCate1);
				}
				if(!"".equals(fileCate2)){
					where.append(" &  fileCate2 ? '%"+fileCate2+"%'");
					url.append("&fileCate2="+fileCate2);
				}
				//文件类别一
				List<String> cate1List = uploadService.getAllFileCate1();
				//文件类别二
				List<String> cate2List = uploadService.getAllFileCate2(fileCate1);
				model.add("cate1List",cate1List);
				model.add("cate2List",cate2List);
				//分页查询
				Paginate<UploadDocInfo> pList;
				pList = uploadService.getListByPage(where.toString(),pageIndex, 20);
			
				model.add("pList",pList);
				if(pList !=null)
					model.add("rsList",pList.getItems());	
				model.add("paramurl",url.toString());
				model.add("initalFileName",initalFileName);
				model.add("fileCate1",fileCate1);
				model.add("fileCate2",fileCate2);
				returnUrl = "uploadDoc/docSearch";
				return ActionResult.view(returnUrl);
		} catch (Exception e) {
			e.printStackTrace();
			return new ContentResult("error");
		}
	}
	
	/**
	 * 上传文档
	 * @return
	 */
	@Path("upload")
	@Check("uploadDoc/manage/manage")
	@POST
	@GET
	public ActionResult updateDoc() {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class, model);
		String returnUrl = "uploadDoc/toUploadDoc";
		try {
				RequestFile file = beat.getClient().getUploads().getFile("pdf_srcFile");
				String fileType = file.getContentType();
				log.info("filename: "+file.getName());
				log.info("originalFilename: "+file.getOriginalFilename());
				log.info("filetype: "+fileType);
				//原始文件名
				String srcName = file.getOriginalFilename();
				String suffix = "";
				if(srcName.lastIndexOf(".") >= 0)
					suffix = srcName.substring(srcName.lastIndexOf(".")+1);
				
				if(acceptTypeMap.containsKey(fileType)){
					fileType = acceptTypeMap.get(fileType);
				}else if(acceptTypeMap.containsKey(suffix)){
					fileType = acceptTypeMap.get(suffix);
				}else{
					model.add("message", "文件格式错误!");
					return ActionResult.view(returnUrl); //文件格式不对，拒绝。
				}
				
				saveFile(request,fileType, suffix);
//				uploadService.saveDocInfo(docInfo);
//				User user = spu.getUserByCookie(request);
//				Timer timer = new Timer();
//				timer.schedule(new MyPdf2swf(user.getUsername(),file.getOriginalFilename(),saveName, fileType),0);
				//文件类别一
				List<String> cate1List = uploadService.getAllFileCate1();
				model.add("cate1List",cate1List);
				model.add("message", "正在转换文档格式,该过程可能持续数分钟,\n转换结果将以邮件形式发送给您,请注意查收反馈邮件!");
				return ActionResult.view(returnUrl); //文件格式不对，拒绝。
		} catch (Exception e) {
			e.printStackTrace();
			model.add("message", "上传失败!");
			return ActionResult.view(returnUrl);   //出现异常
		}
	}

	/**
	 * 转换,保存文件
	 * @param request
	 * @param fileType文件MIME类型
	 * @param suffix文件后缀
	 * @return
	 * @throws Exception
	 */
	private UploadDocInfo saveFile(HttpServletRequest request,String fileType, String suffix) throws Exception{
		User user = spu.getUserByCookie(request);
		RequestFile file = beat.getClient().getUploads().getFile("pdf_srcFile");
		UploadDocInfo docInfo = new UploadDocInfo();
		//保存的文件名
		String saveName = System.currentTimeMillis()+(int)(Math.random()*100000)+"."+suffix;
		docInfo.setUploadTime(new Date());
		docInfo.setInitalFileName(file.getOriginalFilename());
		docInfo.setSaveName(saveName);
		docInfo.setFileCreater(user.getUsername());
		docInfo.setFileType(fileType);
		docInfo.setFileSize(file.getSize());
		docInfo.setFileCate1(ServletRequestUtils.getStringParameter(request, "fileCate1","").trim());
		docInfo.setFileCate2(ServletRequestUtils.getStringParameter(request, "fileCate2","").trim());
		docInfo.setFileDescribe(ServletRequestUtils.getStringParameter(request, "fileDescribe","").trim());
		docInfo.setState(1);
		String destPath = MyPathUtil.getDocSavePath() + saveName;
		file.transferTo(new File(destPath));
		Timer timer = new Timer();
		timer.schedule(new MyPdf2swf(docInfo),0);
		return docInfo;
		
	}
	
	
	/**
	 * 文档信息修改
	 * @param option
	 * @return
	 */
	@Path("update")
	@Check("uploadDoc/manage/manage")
	@POST
	@GET
	public ActionResult updateDocInfo() {
		HttpServletRequest request = beat.getRequest();
		Model model = beat.getModel();
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class, model);
		String returnUrl = "/uploadDoc/editFileInfo";
		int id = 0;
		try {
			id = ServletRequestUtils.getIntParameter(request, "fileID", 0);
			UploadDocInfo docInfo = uploadService.findById(UploadDocInfo.class,"*", id);
			//保存的文件名
			String newCate1 = ServletRequestUtils.getStringParameter(request, "fileCate1","");
			String newCate2 = ServletRequestUtils.getStringParameter(request, "fileCate2","");
			String fileDescribe = ServletRequestUtils.getStringParameter(request, "fileDescribe","").trim();
			docInfo.setFileCate1(newCate1);
			docInfo.setFileCate2(newCate2);
			docInfo.setFileDescribe(fileDescribe);
			if(!uploadService.update(docInfo))
				return new ContentResult("error");
			//文件类别一
			List<String> cate1List = uploadService.getAllFileCate1();
			//文件类别二
			List<String> cate2List = uploadService.getAllFileCate2(docInfo.getFileCate1());
			model.add("cate1List",cate1List);
			model.add("cate2List",cate2List);
			model.add("vo",docInfo);
			model.add("message","success");
			return ActionResult.view(returnUrl);
		} catch (Exception e) {
			e.printStackTrace();
			model.add("message","error");
			return ActionResult.view(returnUrl);
		}
	}
	
	
	 /**
	 * 文档阅读
	 * @param option
	 * @return
	 */
	@Path("showDetail")
	@POST
	@GET
	public ActionResult showFile() {
		HttpServletRequest request = beat.getRequest();
		try {
			String fileName = ServletRequestUtils.getStringParameter(request, "fileName","");
			String saveName = ServletRequestUtils.getStringParameter(request, "saveName","");
			String fileType = ServletRequestUtils.getStringParameter(request, "fileType","");
			return showPage(fileName, saveName, fileType);
		} catch (Exception e) {
			e.printStackTrace();
			return ActionResult.redirect("manage/show");
		}
	}
	
	
	private ActionResult showPage(String fileName,String saveName,String fileType){
		Model model = beat.getModel();
		model.add("fileName", fileName);
		model.add("saveName", saveName);
		model.add("fileType", fileType);
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class, model);
		String returnUrl = "uploadDoc/showPlainFile";
		String result = "";
		try {
			if(saveName.lastIndexOf(".") >= 0)
				saveName = saveName.substring(0,saveName.lastIndexOf("."));
			String filePath = "/documents/"+ saveName;
			File swfFile = new File(MyPathUtil.getDocSavePath() + saveName+".pdf.swf");
			if(swfFile.exists()){
				filePath += ".pdf.swf";
				returnUrl = "uploadDoc/showSwfFile";
			}
			result = "success";
			model.add("srcFile", filePath);
		} catch (Exception e) {
			e.printStackTrace();
			result = "error";
			return ActionResult.redirect("manage/show");
		}
		
		model.add("message", result);
		return ActionResult.view(returnUrl);
	}
	
	
	/**
	 * 文档下载
	 * @param option
	 * @return
	 */
	@Path("download")
	@Check("uploadDoc/manage/manage")
	@POST
	@GET
	public ActionResult downLoadFile() {
		HttpServletRequest request = beat.getRequest();
		HttpServletResponse response = beat.getResponse();
		Model model = beat.getModel();
		TemplateMethodFactory.setVelocityContext("tools", VelocityTools.class, model);
		try {
			String fileName = ServletRequestUtils.getStringParameter(request, "fileName","");
			//文件名编码
			fileName = URLEncoder.encode(fileName,"UTF-8");  
			String saveName = ServletRequestUtils.getStringParameter(request, "saveName","");
			String filePath = MyPathUtil.getDocSavePath() + saveName;
			response.setContentType("application/x-download;charset=UTF8");
			response.addHeader("Content-Disposition", "attachment; filename="+ fileName);
			InputStream input = FileUtil.findFileAsStream(filePath);
			OutputStream output = response.getOutputStream();
			IOUtils.copy(input, output);
			response.flushBuffer();
			IOUtils.closeQuietly(input);
			
		} catch (Exception e) {
			e.printStackTrace();
			return new ContentResult("下载失败");
		}
		
		return new ContentResult("");
	}
	
	
	/**
	 *取得文档类别一列表
	 * @param option
	 * @return
	 */
	@Path("getAllFileCate1")
	@POST
	@GET
	public ActionResult getAllFileCate1() {
		return new ActionResult() {
			@Override
			public void render(BeatContext beat) {
				try {
					HttpServletResponse response = beat.getResponse();
					List<String> cate1List = uploadService.getAllFileCate1();
					StringBuilder sb = new StringBuilder("[");
					for (int i = 0; i < cate1List.size(); i++) {
						String cate1 = cate1List.get(i);
						sb.append("{'value':'" + cate1 + "'}");
						if ((i + 1) < cate1List.size()) {
							sb.append(",");
						}
					}
					sb.append("]");
					JSONArray array = JSONArray.fromObject(sb.toString());
					response.setContentType("text/plain; charset=utf-8");
					PrintWriter pw = response.getWriter();
					pw.write(array.toString());
					response.flushBuffer();
					IOUtils.closeQuietly(pw);
					// log.info(array.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		};
	}
	
	
	/**
	 *取得文档类别二列表
	 * @param option
	 * @return
	 */
	@Path("getAllFileCate2")
	@POST
	@GET
	public ActionResult getAllFileCate2(){
		return new ActionResult() {
			@Override
			public void render(BeatContext beat) {
				try {
					HttpServletRequest request = beat.getRequest();
					HttpServletResponse response = beat.getResponse();
					String fileCate1 = ServletRequestUtils.getStringParameter(
							request, "fileCate1", "");

					List<String> cate2List = uploadService.getAllFileCate2(fileCate1);
					StringBuilder sb = new StringBuilder("[");
					for (int i = 0; i < cate2List.size(); i++) {
						String cate2 = cate2List.get(i);
						sb.append("{'value':'" + cate2 + "'}");
						if ((i + 1) < cate2List.size()) {
							sb.append(",");
						}
					}
					sb.append("]");
					JSONArray array = JSONArray.fromObject(sb.toString());
					response.setContentType("text/plain; charset=utf-8");
					PrintWriter pw = response.getWriter();
					pw.write(array.toString());
					response.flushBuffer();
					IOUtils.closeQuietly(pw);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
	}
	
	/**
	 * 删除文件,源文件和pdf,swf文件都删除
	 * @param fileName
	 * @return
	 */
	public static boolean deleteFile(String fileName){
		
		String prefix = fileName;
		if(fileName.indexOf(".") > 0 ){
			prefix = prefix.substring(0,prefix.lastIndexOf("."));
		}
		prefix = MyPathUtil.getDocSavePath()+prefix;
		File srcFile = new File(prefix);
		File pdfFile = new File(prefix+".pdf");
		File swfFile = new File(prefix+".pdf.swf");
		
		FileUtil.deleteFile(srcFile);
		FileUtil.deleteFile(pdfFile);
		FileUtil.deleteFile(swfFile);
		return true;
	}
	
	
	public static boolean acceptFile(String sufffix){
		return acceptTypeMap.containsKey(sufffix);
	}
	
	
	public static String getMimeType(String sufffix){
		return acceptTypeMap.get(sufffix);
	}
	
}
